package com.qbm.association.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qbm.association.bean.ClubStatusEnum;
import com.qbm.association.bean.JoinClubPowerEnum;
import com.qbm.association.bean.JoinClubStatusEnum;
import com.qbm.association.bean.ResultBean;
import com.qbm.association.config.Audience;
import com.qbm.association.entity.Club;
import com.qbm.association.entity.JoinClub;
import com.qbm.association.entity.Student;
import com.qbm.association.mapper.ClubMapper;
import com.qbm.association.service.ClubService;
import com.qbm.association.service.JoinClubService;
import com.qbm.association.service.StudentService;
import com.qbm.association.util.JWTTokenUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Aron
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/association/joinClub")
public class JoinClubController {

    @Resource
    private ClubMapper clubMapper;

    @Resource
    private JoinClubService joinClubService;

    @Resource
    private ClubService clubService;

    @Autowired
    private Audience audience;

    @Resource
    private StudentService studentService;

    @GetMapping("getAllCanJoinClubByStatus")
    public ResultBean getAllCanJoinClubByStatus(Integer currentPage, String clubName, HttpServletRequest request) {
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        // 排除已经提出申请或已经加入的社团
        List<JoinClub> joinClublist = joinClubService.list(queryWrapper);
        QueryWrapper<Club> queryWrapper1 = new QueryWrapper<>();
        for (int i = 0; i < joinClublist.size(); i++) {
            queryWrapper1.ne("id", joinClublist.get(i).getClubId());
        }
        queryWrapper1.eq("club_status", ClubStatusEnum.SUCCESS.getCode());
        if (clubName != null && clubName.length() != 0) {
            queryWrapper1.like("name", clubName);
        }
        Page<Club> page = new Page<>(currentPage, 5);
        Page<Club> page1 = clubMapper.selectPage(page, queryWrapper1);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("joinClub")
    public ResultBean joinClub(Integer clubId, HttpServletRequest request) {
        JoinClub joinClub = new JoinClub();
        int userId = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId();
        joinClub.setUserId(userId);
        joinClub.setClubId(clubId);
        joinClub.setUserPower(JoinClubPowerEnum.MEMBER.getCode());
        joinClub.setJoinClubStatus(JoinClubStatusEnum.WAITING.getCode());
        // 查找此人是否已经加入该社团
//        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId).eq("club_id", clubId);
//        JoinClub joinClub2 = joinClubService.getOne(queryWrapper);
//        if (null != joinClub2) {
//            return ResultBean.fail("已存在该成员申请");
//        }
        boolean isTrue = joinClubService.save(joinClub);
        Assert.isTrue(isTrue, "加入失败");
        return ResultBean.success("请等待审核");
    }

    @GetMapping("getAllApplyJoinClubByStatus")
    public ResultBean getAllApplyJoinClubByStatus(Integer currentPage, String clubName, HttpServletRequest request) {
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("join_club_status", JoinClubStatusEnum.WAITING.getCode());
        // 排除已经提出申请或已经加入的社团
        List<JoinClub> joinClublist = joinClubService.list(queryWrapper);
        if (joinClublist.size() == 0) {
            return ResultBean.success(new Page<>(currentPage, 5), "没有数据");
        }
        QueryWrapper<Club> queryWrapper1 = new QueryWrapper<>();
        if (clubName != null && clubName.length() != 0) {
            queryWrapper1.like("name", clubName);
        }
        queryWrapper1.and(wrapper -> {
            for (int i = 0; i < joinClublist.size(); i++) {
                if (i != joinClublist.size() - 1) {
                    wrapper.eq("id", joinClublist.get(i).getClubId()).or();
                } else {
                    wrapper.eq("id", joinClublist.get(i).getClubId());
                }
            }
        });
        queryWrapper1.orderByDesc("create_time");
        Page<Club> page = new Page<>(currentPage, 5);
        Page<Club> page1 = clubMapper.selectPage(page, queryWrapper1);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("getAllMyClubByStatus")
    public ResultBean getAllMyClubByStatus(Integer currentPage, String clubName, HttpServletRequest request) {
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("join_club_status", JoinClubStatusEnum.SUCCESS.getCode());
        List<JoinClub> joinClublist = joinClubService.list(queryWrapper);
        if (joinClublist.size() == 0) {
            return ResultBean.success(new Page<>(currentPage, 5), "没有数据");
        }
        QueryWrapper<Club> queryWrapper1 = new QueryWrapper<>();
        if (clubName != null && clubName.length() != 0) {
            queryWrapper1.like("name", clubName);
        }
        queryWrapper1.and(wrapper -> {
            for (int i = 0; i < joinClublist.size(); i++) {
                if (i != joinClublist.size() - 1) {
                    wrapper.eq("id", joinClublist.get(i).getClubId()).or();
                } else {
                    wrapper.eq("id", joinClublist.get(i).getClubId());
                }
            }
        });
        queryWrapper1.orderByDesc("create_time");
        Page<Club> page = new Page<>(currentPage, 5);
        Page<Club> page1 = clubMapper.selectPage(page, queryWrapper1);
        return ResultBean.success(page1, "获取成功");
    }

    @GetMapping("setPreManager")
    public ResultBean setPreManager(Integer clubId, Integer id, HttpServletRequest request) {
//        社长退团
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("club_id", clubId);
        boolean isRemove = joinClubService.remove(queryWrapper);
        Assert.isTrue(isRemove, "社长退团失败");
//        设置新任社长
        UpdateWrapper<JoinClub> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", id);
        updateWrapper.eq("club_id", clubId);
        updateWrapper.set("user_power", JoinClubPowerEnum.DIRECTOR.getCode());
        boolean isUpdate = joinClubService.update(updateWrapper);
        Assert.isTrue(isUpdate, "设置新任社长失败");
//      设置club创建人
        UpdateWrapper<Club> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("id", clubId);
        updateWrapper1.set("create_user_id", id);
        boolean isUpdate1 = clubService.update(updateWrapper1);
        Assert.isTrue(isUpdate1,"设置club创建人失败");

        return ResultBean.success("操作成功");
    }

    @GetMapping("quitClub")
    public ResultBean quitClub(Integer clubId, HttpServletRequest request) {
//        社长退团
        QueryWrapper<JoinClub> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getId());
        queryWrapper.eq("club_id", clubId);
        boolean isRemove = joinClubService.remove(queryWrapper);
        Assert.isTrue(isRemove, "退团失败");

        return ResultBean.success("操作成功");
    }
}

